package cn.kimming.rpc.remoting.proxy.jdk;

import cn.kimming.rpc.common.exception.RpcException;
import cn.kimming.rpc.remoting.client.RpcClient;
import cn.kimming.rpc.remoting.transport.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class JDKClientProxyInnovationHandler implements InvocationHandler {

    private RpcClient rpcClient;

    public JDKClientProxyInnovationHandler(RpcClient rpcClient) {
        this.rpcClient = rpcClient;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        if ("finalize".equals(methodName)) {
            return method.invoke(proxy, args);
        }
        RpcResponse response = rpcClient.doRpc(method, args);
        if (!response.getSuccess()) {
            throw new RpcException(response.getError().getMessage(), response.getError());
        }
        return response.getResult();
    }

}

